package com.zjc.yohoshop.mvp.view.fragment;


import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.zjc.yohoshop.R;
import com.zjc.yohoshop.mvp.view.alipay.AuthResult;
import com.zjc.yohoshop.mvp.view.alipay.PayResult;
import com.zjc.yohoshop.mvp.view.alipay.util.OrderInfoUtil2_0;

import java.text.DecimalFormat;
import java.util.Map;

/**
 * 支付中心
 * A simple {@link Fragment} subclass.
 */
public class PayCenterFragment extends Fragment implements View.OnClickListener {

    private double sumPrice = 0;

    private View view;
    private TextView tv_pay_center_sumprice;
    private RadioButton rb_pay_center_ali_pay;
    private RadioButton rb_pay_center_ali_hb_pay;
    private TextView tv_pay_center_ali_hb_pay_select;
    private RadioButton rb_pay_center_pay_wx;
    private RadioButton rb_pay_center_pay_yunsf;
    private RadioButton rb_pay_center_vpadpay;
    private RadioGroup rg_pay_center;
    //TODO 花呗选择
    private PopupWindow ali_hb_pop;
    private RadioGroup rg_item_pay_center_popupwindow;//选择按钮组
    private int default_hb = R.id.rb_item_pay_center_popupwindow_3q;
    private TextView tv_item_pay_center_popupwindow_sumprice;//使用花呗总金额
    private DecimalFormat df;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_pay_center, container, false);
        initView(view);
        initListener();
        initDAta();
        return view;
    }

    //初始化数据
    private void initDAta() {
        sumPrice = getArguments().getDouble("sumPrice");
        tv_pay_center_sumprice.setText("￥" + sumPrice);
        tv_pay_center_ali_hb_pay_select.setText("￥" + df.format((sumPrice / 3)) + "*3期");
    }

    //添加监听事件
    private void initListener() {
        view.findViewById(R.id.iv_pay_center_back).setOnClickListener(this);//返回上一页
        view.findViewById(R.id.cob_pay_center_pay).setOnClickListener(this);//支付按钮
        view.findViewById(R.id.ll_pay_center_ali_pay).setOnClickListener(this);//支付宝
        view.findViewById(R.id.ll_pay_center_ali_hb_pay).setOnClickListener(this);//花呗分期
        view.findViewById(R.id.ll_pay_center_ali_hb_pay_select).setOnClickListener(this);//还款方式
        view.findViewById(R.id.ll_pay_center_pay_wx).setOnClickListener(this);//微信支付
        view.findViewById(R.id.ll_pay_center_pay_yunsf).setOnClickListener(this);//云闪付
        view.findViewById(R.id.ll_pay_center_vpadpay).setOnClickListener(this);//招行一网通
        rg_pay_center.check(R.id.rb_pay_center_ali_pay);

    }

    //初始化控件
    private void initView(View view) {
        tv_pay_center_sumprice = (TextView) view.findViewById(R.id.tv_pay_center_sumprice);//总金额
        rb_pay_center_ali_pay = (RadioButton) view.findViewById(R.id.rb_pay_center_ali_pay);
        rb_pay_center_ali_hb_pay = (RadioButton) view.findViewById(R.id.rb_pay_center_ali_hb_pay);
        tv_pay_center_ali_hb_pay_select = (TextView) view.findViewById(R.id.tv_pay_center_ali_hb_pay_select);
        rb_pay_center_pay_wx = (RadioButton) view.findViewById(R.id.rb_pay_center_pay_wx);
        rb_pay_center_pay_yunsf = (RadioButton) view.findViewById(R.id.rb_pay_center_pay_yunsf);
        rb_pay_center_vpadpay = (RadioButton) view.findViewById(R.id.rb_pay_center_vpadpay);
        rg_pay_center = (RadioGroup) view.findViewById(R.id.rg_pay_center);

        df = new DecimalFormat("#.##");//保留两位小数
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_pay_center_back://返回上一页
                getActivity().finish();
                break;
            case R.id.ll_pay_center_ali_pay://支付宝
                rg_pay_center.check(R.id.rb_pay_center_ali_pay);
                break;
            case R.id.ll_pay_center_ali_hb_pay://花呗分期
                rg_pay_center.check(R.id.rb_pay_center_ali_hb_pay);
                break;
            case R.id.ll_pay_center_ali_hb_pay_select://还款方式
                rg_pay_center.check(R.id.rb_pay_center_ali_hb_pay);
                ali_hb_popupwindow();
                break;
            case R.id.ll_pay_center_pay_wx://微信支付
                rg_pay_center.check(R.id.rb_pay_center_pay_wx);
                break;
            case R.id.ll_pay_center_pay_yunsf://云闪付
                rg_pay_center.check(R.id.rb_pay_center_pay_yunsf);
                break;
            case R.id.ll_pay_center_vpadpay://招行一网通
                rg_pay_center.check(R.id.rb_pay_center_vpadpay);
                break;
            case R.id.cob_pay_center_pay://支付按钮
                switch (rg_pay_center.getCheckedRadioButtonId()) {
                    case R.id.rb_pay_center_ali_pay://支付宝支付
                        requestPermission();
                        break;
                    case R.id.rb_pay_center_ali_hb_pay://花呗分期
                        break;
                    case R.id.rb_pay_center_pay_wx://微信支付
                        break;
                    case R.id.rb_pay_center_pay_yunsf://云闪付
                        break;
                    case R.id.rb_pay_center_vpadpay://招行一网通
                        break;
                }
                break;
            case R.id.iv_item_pay_center_popupwindow_close://关闭花呗分期窗口
                ali_hb_pop.dismiss();
                break;
            case R.id.rl_item_pay_center_popupwindow_3q://3期
                default_hb = R.id.rb_item_pay_center_popupwindow_3q;
                rg_item_pay_center_popupwindow.check(default_hb);
                ali_hb_pop.dismiss();
                break;
            case R.id.rl_item_pay_center_popupwindow_6q://6期
                default_hb = R.id.rb_item_pay_center_popupwindow_6q;
                rg_item_pay_center_popupwindow.check(default_hb);
                ali_hb_pop.dismiss();
                break;
            case R.id.rl_item_pay_center_popupwindow_12q://12期
                default_hb = R.id.rb_item_pay_center_popupwindow_12q;
                rg_item_pay_center_popupwindow.check(default_hb);
                ali_hb_pop.dismiss();
                break;
        }
    }

    //花呗分期选择窗口
    public void ali_hb_popupwindow() {
        //TODO 1:实例化对象
        ali_hb_pop = new PopupWindow(getActivity());
        //TODO 2：设置属性
        View view_ali_hb = LayoutInflater.from(getActivity()).inflate(R.layout.item_pay_center_popupwindow, null);
        tv_item_pay_center_popupwindow_sumprice = view_ali_hb.findViewById(R.id.tv_item_pay_center_popupwindow_sumprice);
        rg_item_pay_center_popupwindow = view_ali_hb.findViewById(R.id.rg_item_pay_center_popupwindow);
        RadioButton rb_item_pay_center_popupwindow_3q = view_ali_hb.findViewById(R.id.rb_item_pay_center_popupwindow_3q);
        RadioButton rb_item_pay_center_popupwindow_6q = view_ali_hb.findViewById(R.id.rb_item_pay_center_popupwindow_6q);
        RadioButton rb_item_pay_center_popupwindow_12q = view_ali_hb.findViewById(R.id.rb_item_pay_center_popupwindow_12q);
        rb_item_pay_center_popupwindow_3q.setText("￥" + df.format((sumPrice / 3)) + "*3期");
        rb_item_pay_center_popupwindow_6q.setText("￥" + df.format((sumPrice / 6)) + "*6期");
        rb_item_pay_center_popupwindow_12q.setText("￥" + df.format((sumPrice / 12)) + "*12期");

        rg_item_pay_center_popupwindow.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId){
                    case R.id.rb_item_pay_center_popupwindow_3q:
                        tv_pay_center_ali_hb_pay_select.setText("￥" + df.format((sumPrice / 3)) + "*3期");
                        tv_item_pay_center_popupwindow_sumprice.setText("￥" + (sumPrice + (6.31 * 3)));
                        break;
                    case R.id.rb_item_pay_center_popupwindow_6q:
                        tv_pay_center_ali_hb_pay_select.setText("￥" + df.format((sumPrice / 6)) + "*6期");
                        tv_item_pay_center_popupwindow_sumprice.setText("￥" + (sumPrice + (6.17 * 6)));
                        break;
                    case R.id.rb_item_pay_center_popupwindow_12q:
                        tv_pay_center_ali_hb_pay_select.setText("￥" + df.format((sumPrice / 12)) + "*12期");
                        tv_item_pay_center_popupwindow_sumprice.setText("￥" + (sumPrice + (5.48 * 12)));
                        break;
                }
            }
        });
        rg_item_pay_center_popupwindow.check(default_hb);

        view_ali_hb.findViewById(R.id.iv_item_pay_center_popupwindow_close).setOnClickListener(this);//关闭窗口事件
        view_ali_hb.findViewById(R.id.rl_item_pay_center_popupwindow_3q).setOnClickListener(this);//3期
        view_ali_hb.findViewById(R.id.rl_item_pay_center_popupwindow_6q).setOnClickListener(this);//6期
        view_ali_hb.findViewById(R.id.rl_item_pay_center_popupwindow_12q).setOnClickListener(this);//12期

        ali_hb_pop.setContentView(view_ali_hb);
        ali_hb_pop.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        ali_hb_pop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        //设置点击外部消失
        ali_hb_pop.setOutsideTouchable(true);
        //TODO 3:展示
        /**
         * @param parent 父布局
         * @param gravity gravity可以是Gravity.TOP、Gravity.BOTTOM、Gravity.LEFT、Gravity.RIGHT。。。。
         * @param x x轴偏移量
         * @param y y轴偏移量
         */
        View parent = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_goods_values, null);

        //1.获得当前窗体的属性
        WindowManager.LayoutParams layoutParams = getActivity().getWindow().getAttributes();
        //2.设置透明度为0.5f,半透明状态
        layoutParams.alpha = 0.5f;
        //3.为窗体设置新属性
        getActivity().getWindow().setAttributes(layoutParams);
        //4.当窗体消失的时候，恢复透明度
        ali_hb_pop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams layoutParams = getActivity().getWindow().getAttributes();
                layoutParams.alpha = 1f;
                getActivity().getWindow().setAttributes(layoutParams);
            }
        });
        ali_hb_pop.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
    }



    //TODO 支付宝沙箱支付
    /*
        账号： dbcxfd6245@sandbox.com
        密码： 111111
     */
    /**
     * 用于支付宝支付业务的入参 app_id。
     */
    public static final String APPID = "2016100100638707";

    /**
     * 用于支付宝账户登录授权业务的入参 pid。
     */
    public static final String PID = "2088702623516211";

    /**
     * 用于支付宝账户登录授权业务的入参 target_id。
     */
    public static final String TARGET_ID = "zzyy112233445566";

    /**
     *  pkcs8 格式的商户私钥。
     *
     * 	如下私钥，RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个，如果两个都设置了，本 Demo 将优先
     * 	使用 RSA2_PRIVATE。RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议商户使用
     * 	RSA2_PRIVATE。
     *
     * 	建议使用支付宝提供的公私钥生成工具生成和获取 RSA2_PRIVATE。
     * 	工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
     */
//    public static final String RSA2_PRIVATE = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCMXMAwxZcuFxtcGXu1LtVr14W/L+TOihZfqAhz2Jqe4HR3WPCxye+gsc2tO8Lekze/LD3toetpKEaYxRh7zZDOzPtPcl7idaewsbJmkEVFfiYzAeLpHKouFJERbR2dONOuCRq1B6I3H6djb2XWBEIlpQUS+SRS9ct/zpoq352PknWFMq0gJUlQdIuriGLeCSYRdZ7zFtbzXqK6N8Jguqiink9lbaLRo+247X5pqtkubSyMGtf7xCHDW3CoLG0TEnrGjv27mVdMXs7V1bt4XfUdQAuBqTN1vVjHZpz4iyyaLYUNpqaf2S4xI7wCBFKMSTc0/cc7Yolqwug/1v5kvOTJAgMBAAECggEAG08keZjIHEiUoyu2HP9auNu7AwK/gsvtJHleA6QeGVFUd7APTJgcjmhpuw3IkWOVUhW6itSZJ+GVMr4OUHAjf4j0UHXRLkBz+vXn3vqs76NmrT/ttStFlSedPgW74E4hKVhOIPC2SAFZoQgYiTZU5FwiC5n7zkRSbrB04GiXkEpFpSjgS/14brT6vhClHKfF4Ue5iX/HgB2cLpVPsx3LShPhVr22D+OFivrCB/q7chouY1QRJ55cRnqlYbEvGQuMdNEI6dVz2aapKVcNfsTliXXD93+R+1d95ojzTEdgKfk/4G/rN4M0r2XWF+APCH2iFYfeRgj3uKLaFhWVYgTnAQKBgQDM1PfDiXtUbJ8euDk1Bj4mw+lJ3MhbtyOJBaVv/oTSjHHIAA4Fb8kSFUhCnSJZzF8jzh5Oe5FsUYWt05Z/4Bpk//XEbpwdECO1Rku/edxT4mPYQs4CCh3U+4yIb1K9L+/ohXFNMryeAaD26X6LfFIBSIfzfyw9e0xztZVzJqbtKQKBgQCvbPEuWr04znGN5UmxzVXRZ/otMJ74Mhwiy9nPUDYmPGq9G/OQqVthn0M8/R+6X0WJbK+nM2TNetnhLglpsOsV1CP6/By8Ao9Tdlu7B27FgGue5HB5lBGGxGLjJHDxU0jWYTkmmmBb2molVHgRIosgGMp5nLTn+w496YcAHi2OoQKBgQDAnu24RktiYxtnyhqSEKLV1ZpGyYbpKNoT+ulO3myNi2FckSCeYDcX+EeRzS8Gfzhg9W5uo6ln0WoCw11eN6LapBG8fb/1XL4XtFl7YN+fSuBV+My+AkF3jm7jxrxqCPB1GzgnPrU9aY6zY3SLO4fqiQjAJTG3R4HntjUqqoiDsQKBgC3Om7fH9+sSdTJhMfocrREOPpR4Qrp6k0A+zLRGtK0NT63r05DtuC/on20Yh6Vp5UV6PO/DCsphDu2u0MRpbyl3CKIsHPC3Fmfr2w4eZb1qyC9oZTpKAL2ZIF1BkcBiR/26y2qaGxlBEkCHKwcGZx/NeWmCEvcUZmaiSR8twiWhAoGAeK7r25GaUoGLJbmbs2N4auoLxdvvg2LPIEgj5Yxt1cXqOM8d1jFMi5k83C6YhWavG+s3VTPHqyslRp0GONoIf/a6ICVfvsacD+ncP9anwWwZY+uDGHdx0h8lezAVwDlDl7PqR1rWObRYP/mjpSsxAAMKoaUdtr628qUrHbFrVWc=";
    public static final String RSA2_PRIVATE ="";
    public static final String RSA_PRIVATE = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC+IXF8TzFYdpU378CZw03OhRmwP1IwpVJSe/tUHK/tTkXhn/lDnqQXLHFRKEyh893hqW8Us8oIq3rFcFHUagj+7IMNg5hngTxV+8u1r+HS917SvpqOOjy/XeVmCjRnpkl0D6f83gnHlkzcnaYe6asjRaI435enNyimu7UCCkwBbbH0Nv3BWLHRtIdvqh4mp7umYdlx2tpH+QJDC9DBCxC/YuIQpCS8b/O5KMLx0LRjRAds8M5yR9O3EajsaoNxemcd7e9bmcMP7ZmkgVNaQPZbO2L4GrdehVJ+enOlJTAYH4ev209pz6HFCAyVkqly41k/icKzmArTY2NPtVINvBUdAgMBAAECggEAc8NrFLQnKGSzQCajTzviAO97j5tOUL4oHH7OrQz2dPemhtTfcTODV3TA3hg6aJVSMJb4QlOhnJvEGbjkqf+R0J1yweSxA7xlXzj7dHlNdyUUwB47foOo/x+NkA6Aj+doa9kogEc1DyfNTrpSLho6EDTSq+w/qxljj/lUIZThaDA0U7ge8yeBIyMyIQ7W550Co/amXgOUq88S7rrGcZ0z0vAsTjFYiuMmMIJdOutbUGkeitvOzXXG500VYPgjOAVyVuJdRfrEMeB2OzhCPhzzfJbBGxPH0UNM+QGT8FOhXFGVX981e3OrJeBkB/6BqXSLOVuo6resNvQPJCsmJDXPxQKBgQDjehPOKYVs46BxhObVxbUyqr6kuy1JZZFywJ0jUiSI91AdjZAPUEAFGWOm3RoGYOqxHBG2+if82XtJW0tabd6xJZtMrgMCuG+d4VHHIe6GM0A0WyC3GzIeH7xdbYXKnCURo0hzMOrbY6GMuiYEKd7weYAtF88Z68w5BS2lesAsAwKBgQDV+JDjPWA19Vhbt3h75i4JqpgmWErqe0hRh7HpUeeKjv5+Lq138eBpKdeQAHZbGJN7TuMFKfdhZxKoVPDC/i0peuGcj9VQknxByKyfWvBq2Nf+pSg5zcjqbCJ6UDxI04nLBtP4LvR58syT9gUU3Wa+GeO30FmoPpPImZfsOHlAXwKBgQC5eKDLWIlkZhg8VqtLo38BB7yXXdIn5Pt5f9jfoqsNTfBxmCncgocgYToiJGaCyuSwcX10HnUaMUzXW+uNmMWY1FvSYpMr1auUI9HktiLgIst3pNGA2li7vQ59cr5Cm5uRzPtWiI0FQi/HKUOz41vV4IsEuUPwE5UY7MLyCKrFdwKBgQCRnFlFO0RZFACwUbf9YRRdYamvFpDM5168lQJ+zE0snskTp8JHCOR1zJK0nYvtzFi5JmMZ5YhC0bkBsuQxXnXvb39PYxaAgV9sCRtoSqOnoq/CzDQGukMLPNFtuWJ9EPAJqTjhAVtADfooitjEbTL5FXdBZNlOxF8fuV6I05m4MwKBgH1cb7L7Af6HVE6jU9oWTX7oxrLAga0EGdzqOWHAlrjVRh/tgc6CIIJDO055rxRS1QogB05U5MTwtmhQ/beoy83WCx5QiquLB+95NTw77mLNyRwBJFv4vdgVd5RVYH4EVnj/EZu1ZIwWL4MWJ9qcWfh4UOCP6cVtSM+5Jw6kNxMl";

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();



                    Log.d("zfb", "handleMessage: resultinfo => "+resultInfo+" result state => "+resultStatus);
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        showAlert(getActivity(), "Payment success: " + payResult);
                        getActivity().finish();

                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        showAlert(getActivity(), "Payment failed: " + payResult);
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        showAlert(getActivity(), "Authentication success: " + authResult);
                    } else {
                        // 其他状态值则为授权失败
                        showAlert(getActivity(), "Authentication failed: " + authResult);
                    }
                    break;
                }
                default:
                    break;
            }
        };
    };
    private Thread payThread;



    /**
     * 获取权限使用的 RequestCode
     */
    private static final int PERMISSIONS_REQUEST_CODE = 1002;

    /**
     * 检查支付宝 SDK 所需的权限，并在必要的时候动态获取。
     * 在 targetSDK = 23 以上，READ_PHONE_STATE 和 WRITE_EXTERNAL_STORAGE 权限需要应用在运行时获取。
     * 如果接入支付宝 SDK 的应用 targetSdk 在 23 以下，可以省略这个步骤。
     */
    private void requestPermission() {
        // Here, thisActivity is the current activity
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(getActivity(),
                    new String[]{
                            Manifest.permission.READ_PHONE_STATE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE
                    }, PERMISSIONS_REQUEST_CODE);

        } else {
            showToast(getActivity(), "Required permissions have already been granted to AlipaySDK");
            payV2();
        }
    }

    /**
     * 权限获取回调
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PERMISSIONS_REQUEST_CODE: {

                // 用户取消了权限弹窗
                if (grantResults.length == 0) {
                    showToast(getActivity(), "用户取消了权限弹窗");
                    return;
                }

                // 用户拒绝了某些权限
                for (int x : grantResults) {
                    if (x == PackageManager.PERMISSION_DENIED) {
                        showToast(getActivity(), "用户拒绝了某些权限");
                        return;
                    }
                }

                // 所需的权限均正常获取
                showToast(getActivity(), "所需的权限均正常获取");
            }
        }
    }

    /**
     * 支付宝支付业务示例
     */
    public void payV2() {
        if (TextUtils.isEmpty(APPID) || (TextUtils.isEmpty(RSA2_PRIVATE) && TextUtils.isEmpty(RSA_PRIVATE))) {
            showAlert(getActivity(), "Error: Missing \\\"APPID\\\" or \\\"RSA_PRIVATE\\\" in AlipayActivity");
            return;
        }

        /*
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo 的获取必须来自服务端；
         */
        boolean rsa2 = (RSA2_PRIVATE.length() > 0);
        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2, sumPrice);
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);

        String privateKey = rsa2 ? RSA2_PRIVATE : RSA_PRIVATE;
        String sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2);
        final String orderInfo = orderParam + "&" + sign;

        final Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(getActivity());
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        payThread = new Thread(payRunnable);
        payThread.start();
    }

    private static void showAlert(Context ctx, String info) {
        showAlert(ctx, info, null);
    }

    @SuppressLint("NewApi")
    private static void showAlert(final Context ctx, String info, DialogInterface.OnDismissListener onDismiss) {
        new AlertDialog.Builder(ctx)
                .setMessage(info)
                .setPositiveButton("Confirm", null)
                .setOnDismissListener(onDismiss)
                .show();
    }


    private static void showToast(Context ctx, String msg) {
        Toast.makeText(ctx, msg, Toast.LENGTH_LONG).show();
    }

}
